<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目ID" prop="projectId">
        <el-input
          v-model="queryParams.projectId"
          placeholder="请输入项目ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入合同金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同名称" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:contract:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:contract:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:contract:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:contract:export']"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-document"
          size="mini"
          @click="handlePrint"
          v-hasPermi="['project:contract:print']"
        >打印</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-data-analysis"
          size="mini"
          @click="handleStatistic"
          v-hasPermi="['project:contract:statistic']"
        >统计</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同ID" align="center" prop="id" sortable/>
      <el-table-column label="项目ID" align="center" prop="projectId" sortable/>
      <el-table-column label="合同金额" align="center" prop="amount" sortable/>
      <el-table-column label="合同名称" align="center" prop="contractName" sortable/>
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="项目ID" align="center" prop="projectId" />
      <el-table-column label="合同金额" align="center" prop="amount" />
      <el-table-column label="合同名称" align="center" prop="contractName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:contract:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:contract:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['project:contract:view']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改contract对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目ID" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入项目ID" />
        </el-form-item>
        <el-form-item label="合同金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入合同金额" />
        </el-form-item>
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="form.contractName" placeholder="请输入合同名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看contract对话框 -->
    <el-dialog :title="title" :visible.sync="openView" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目ID" prop="projectId">
          <el-input v-model="form.projectId" :disabled="isViewMode" placeholder="请输入项目ID" />
        </el-form-item>
        <el-form-item label="合同金额" prop="amount">
          <el-input v-model="form.amount" :disabled="isViewMode" placeholder="请输入合同金额" />
        </el-form-item>
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="form.contractName" :disabled="isViewMode" placeholder="请输入合同名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelView">返  回</el-button>
      </div>
    </el-dialog>

    <!-- 数据统计对话框 -->
    <el-dialog
      :title="'统计结果'"
      :visible.sync="dialogVisible"
      width="80%"
      :before-close="handleCloseDialog"
      append-to-body
    >
      <div id="echart-container" style="width:700px; height: 400px;"></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { listContract, getContract, delContract, addContract, updateContract } from "@/api/project/contract";
import * as echarts from 'echarts';

export default {
  name: "Contract",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // contract表格数据
      contractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openView: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        amount: null,
        contractName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: "项目ID不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "合同金额不能为空", trigger: "blur" }
        ],
        contractName: [
          { required: true, message: "合同名称不能为空", trigger: "blur" }
        ]
      },
      isViewMode: false,
      dialogVisible: false,
      chartData: {
        contract: [],
        amount: []
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询contract列表 */
    getList() {
      this.loading = true;
      listContract(this.queryParams).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelView() {
      this.openView = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        amount: null,
        contractName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;

      this.title = "添加合同";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getContract(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改合同";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateContract(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除合同编号为"' + ids + '"的数据项？').then(function() {
        return delContract(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/contract/export', {
        ...this.queryParams
      }, `contract_${new Date().getTime()}.xlsx`)
    },
    /** 查看按钮 **/
    handleView(row) {
      console.log("clicked view button");
      this.reset();
      const id = row.id || this.ids
      getContract(id).then(response => {
        this.form = response.data;
        this.openView = true;
        this.title = "查看合同";
        this.isViewMode = true;
      });
    },
    /** 打印按钮操作 **/
    handlePrint() {
      // 获取表格的 DOM 元素
      const printContent = document.querySelector('.el-table');

      // 创建一个新的窗口来打印内容
      const newWindow = window.open('', '_blank');

      const tableHeader = printContent.querySelector('thead'); // 获取表头
      const tableRows = printContent.querySelectorAll('tbody tr'); // 获取所有行

      let printContentHTML = '<table border="1">'; // 创建一个新的表格开始标签

      //表头
      if (tableHeader) {
        // 获取表头的所有列
        const headerCells = tableHeader.querySelectorAll('th');
        let headerHTML = '<tr>';

        // 只保留指定的列
        const columnIndexes = [1, 2, 3, 4]; // 例如：设备ID, 设备名称, 检查时间列索引
        columnIndexes.forEach(index => {
          if (headerCells[index]) {
            headerHTML += `<th>${headerCells[index].innerHTML}</th>`; // 获取指定列的表头并插入
          }
        });

        headerHTML += '</tr>';
        printContentHTML += headerHTML; // 将表头添加到打印内容中
      }

      // 遍历表格的每一行，提取指定列的数据
      tableRows.forEach((row, rowIndex) => {
        // 跳过表头行或其他无效行
        const cells = row.querySelectorAll('td'); // 获取每一行的所有单元格
        if (cells.length > 0) {
          // 只提取你需要的列，假设你需要第1列、2列和4列
          let rowHTML = '<tr>';
          // 指定需要的列索引（从0开始）
          const columnIndexes = [1, 2, 3, 4];  // 例如：设备ID, 设备名称, 检查时间列索引
          columnIndexes.forEach(index => {
            if (cells[index]) {
              rowHTML += `<td>${cells[index].innerHTML}</td>`; // 获取指定列的数据并插入到新行
            }
          });
          rowHTML += '</tr>';
          printContentHTML += rowHTML; // 将处理过的行添加到打印内容中
        }
      });

      printContentHTML += '</table>'; // 结束表格标签

      // 打开新的打印窗口并写入数据
      newWindow.document.write('<html><head><title>打印</title></head><body>');
      newWindow.document.write(printContentHTML); // 将格式化后的内容写入打印窗口
      newWindow.document.write('</body></html>');
      newWindow.document.close(); // 关闭文档写入
      newWindow.print(); // 执行打印操作
    },
    /** 统计按钮操作 **/
    handleStatistic() {
      // 显示统计对话框
      this.dialogVisible = true;

      // 调用后端接口获取统计数据
      listContract(this.queryParams).then(response => {
        // 假设后端返回的数据包含 rows，contractName 和 amount 字段
        const contractNames = response.rows.map(item => item.contractName);
        const amounts = response.rows.map(item => item.amount);

        // 更新 chartData
        this.chartData = { contract: contractNames, amount: amounts };

        // 渲染图表
        this.$nextTick(() => {
          this.renderChart(); // 渲染图表
        });
      }).catch(error => {
        console.error("获取合同数据失败", error);
      });
    },

    renderChart() {
      var myChart = echarts.init(document.getElementById('echart-container')); // 获取图表容器
      var option = {
        title: {
          text: '统计',
        },
        tooltip: {},
        legend: {
          data: ['金额'],
        },
        xAxis: {
          data: this.chartData.contract,
        },
        yAxis: {},
        series: [
          {
            name: '金额',
            type: 'bar',
            data: this.chartData.amount,
          },
        ],
      };
      myChart.setOption(option); // 设置图表的配置项和数据
    },

    /** 关闭对话框时的处理 */
    handleCloseDialog(done) {
      this.dialogVisible = false;
    },
  }
};
</script>
